<?php

declare(strict_types=1);

namespace App\Console\Commands;

use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Psr\Container\ContainerInterface;
use Hyperf\Contract\ConfigInterface;
use Hyperf\HttpServer\Router\DispatcherFactory;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;

#[Command]
class RouteListCommand extends HyperfCommand
{
    public function __construct(ContainerInterface $container)
    {
        parent::__construct('route:list');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $factory = $this->container->get(DispatcherFactory::class);
        $router = $factory->getRouter('http');
        $routes = $router->getData();

        $config = $this->container->get(ConfigInterface::class);
        $server = $config->get('server.servers.0', ['host' => '0.0.0.0', 'port' => 9501]);
        $domain = "http://{$server['host']}:{$server['port']}";


        $rows = [];
        foreach ($routes as $routeGroup) {
            // POST GET
            if (is_array($routeGroup) && !empty($routeGroup)) {
                foreach ($routeGroup as $httpMethod => $routeItems) {
                    // route object
                    if (is_array($routeItems) && !empty($routeItems)) {
                        foreach ($routeItems as $url => $routeItem) {
                            $uri = $domain . $routeItem->route;
                            $rows[] = [
                                $httpMethod,
                                $uri,
                                $this->formatHandler($routeItem->callback),
                            ];
                        }
                    }
                }
            }

        }

        $table = new Table($output);
        $table->setHeaders(['Method', 'URI', 'Handler'])
            ->setRows($rows);
        $table->render();

        return SymfonyCommand::SUCCESS;
    }

    private function formatHandler($handler): string
    {
        if (is_array($handler) && isset($handler[0], $handler[1])) {
            return $handler[0] . '@' . $handler[1];
        }
        return is_string($handler) ? $handler : 'Closure';
    }

    public function handle()
    {
        // TODO: Implement handle() method.
    }
}


